from entity.assemble import Assemble
from entity.modes import CheckLog
from utils.db_tools import insert_batch
from utils.date_tools import str_to_datetime, timestamp_to_datetime, date_operation_day
from check_log_grab.chek_log_reptile import CheckLogReptile
from utils.db_tools import read_db
from config import REPTILE_PATH, FMT
import pandas as ps


class CheckLogApi(object):

    @classmethod
    def get_check_log(cls, start_date: str, end_date=""):
        sql = "SELECT check_id, user_code,user_name,check_in_time FROM check_log "
        if end_date is not None:
            end_date = date_operation_day(end_date, FMT, 1)
            sql = sql + f"WHERE check_in_time BETWEEN '{start_date}' AND '{end_date}';"
        else:
            sql = sql + f"WHERE DATE_FORMAT(check_in_time,'%%Y-%%m-%%d') = '{start_date}'"
        pdf = read_db(sql)
        pdf['check_in_time'] = ps.to_datetime(pdf['check_in_time'])
        return pdf.to_dict(orient='records')


class CheckLogCollector(object):
    def __init__(self, dates: list, users: dict, fmt="%Y-%m-%d"):
        self.fmt = fmt
        self.dates = dates
        self.users = users
        self.daily_data = {date: [] for date in self.dates}
        self.check_data = []

    def analysis_check_data(self):
        """
        整理考勤数据
        :param :
        :return:
        """
        user_info = self.users.get("user", {})
        clr = CheckLogReptile(REPTILE_PATH)
        clr.load_check_in_data(self.dates, self.users, out_file=True)
        check_data = clr.get_check_in_data()
        for cd in check_data:
            uid = cd['userid']
            self.daily_data[timestamp_to_datetime(cd['checkin_time']).strftime(self.fmt)].append(
                Assemble.check_log(uid,
                                   user_info.get(uid, {}),
                                   cd['checkin_time'],
                                   cd['deviceid'],
                                   cd['location_title'],
                                   cd['location_detail'],
                                   cd['groupname'],
                                   cd['checkin_type']
                                   )
            )

    def submit_data(self):
        """
        提交保存考勤数据
        :return:[]
        """
        result = []
        for date in self.dates:
            daily = self.daily_data[date]
            if len(daily):
                insert_batch(CheckLog, daily, f"CheckLog_err-{date}.json")
                result.append(date)
        return result
